package uem;

import com.db4o.Db4oEmbedded;
import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;

public class OperateDB4O {

	final static String BDPer = "./../db4o-8.0/DBPeople.yap";

	public static void main(String[] args) throws IllegalStateException {

		Person person = new Person(null, null);

		ObjectContainer db = Db4oEmbedded.openFile(
				Db4oEmbedded.newConfiguration(), BDPer);

		// run through the database

		ObjectSet<Person> result = db.queryByExample(person);
		if (result.size() == 0)
			System.out.println("there aren't any register of person...");
		else {
			System.out.println("Number of registers: " + result.size());
			while (result.hasNext()) {
				Person p = result.next();
				System.out.println("Name: " + p.getName() + " city: "
						+ p.getCity());
			}

		}

		// Obtain objects person with name Juan
		Person p1 = new Person("Juan", null);
		ObjectSet<Person> result1 = db.queryByExample(p1);

		if (result1.size() != 0) {
			person = (Person) result1.next();
			System.out.println("Name: " + person.getName());
		} else
			System.out.println("No existe Juan...");

		// Obtain objects Person with citiy Guadalajara
		Person p2 = new Person(null, "Guadalajara");
		ObjectSet<Person> result2 = db.queryByExample(p2);

		if (result2.size() != 0) {
			person = (Person) result2.next();
			System.out.println(" city: " + person.getCity());
		} else
			System.out.println("No existe Guadalajara...");

		// Modify an object
		// Look for the object

		ObjectSet<Person> result3 = db.queryByExample(new Person("Juan", null));
		if (result3.size() == 0)
			System.out.println("No existe Juan...");
		else { // modify the city
			person = (Person) result3.next();
			person.setCity("Toledo");
			db.store(person); // modified city
			// show data
			result3 = db.queryByExample(new Person("Juan", null));
			person = (Person) result3.next();
			System.out.println("Name: " + person.getName() + "New city: "
					+ person.getCity());
		}

		// Delete an object
		ObjectSet<Person> result4 = db.queryByExample(new Person("Juan", null));
		if (result4.size() == 0)
			System.out.println("No existe Juan...");
		else { // modify the city
			person = (Person) result4.next();
			System.out.println("Registerts to delete: " + person.getName()
					+ " " + person.getCity());
			if (result4.size() > 1) {// many Juan registers
				while (result4.hasNext()) {
					person = result.next();
					db.delete(person);
					System.out.println("Borrado");

				}
			} else db.delete(person);
		}

		db.close();

	} // end main
}
